package engine.systems.ui.button
{
	import engine.classes.enumerations.SystemPriority;
	import engine.systems.input.interaction.Interaction;
	import engine.systems.update.GameSystem;
	
	public class ButtonSystem extends GameSystem
	{
		public function ButtonSystem()
		{
			super(ButtonNode, updateNode, nodeAdded, nodeRemoved);
			
			this.priority = SystemPriority.POST_UPDATE;
		}
		
		private function updateNode(node:ButtonNode, time:Number):void
		{
			var button:Button = node.button;
			
			if(button.locked) return;
			
			if(!button._invalidate) return;
			button._invalidate = false;
			
			var frame:String;
			
			if(button._isDown)
			{
				button._isDown = false;
				frame = Interaction.DOWN;
			}
			if(button._isOver)
			{
				button._isOver = false;
				frame = Interaction.OVER;
			}
			if(button._isOut)
			{
				button._isOut = false;
				frame = Interaction.OUT;
			}
			
			frame = button.prefix + "_" + frame;
			
			if(button.animated) node.timeline.gotoAndPlay(frame);
			else 				node.timeline.gotoAndStop(frame);
		}
		
		private function nodeAdded(node:ButtonNode):void
		{
			node.interaction.down.add(node.button.down);
			node.interaction.up.add(node.button.over);
			node.interaction.over.add(node.button.over);
			node.interaction.out.add(node.button.out);
		}
		
		private function nodeRemoved(node:ButtonNode):void
		{
			node.interaction.down.remove(node.button.down);
			node.interaction.up.remove(node.button.over);
			node.interaction.over.remove(node.button.over);
			node.interaction.out.remove(node.button.out);
		}
	}
}